(function(document, undefined){
  
var Forum = window.Forum || {};

Forum.Show = (function(){
  
  var $dlg = $('#post-dialog');
  var $posting = $('#posting');
  var $form = $('#post-form');
  var dlgOpt = {
    autoOpen: false,
    closeOnEscape: true,
    width: 650,
    modal: true,
    position: ['center', 'center'],
    zIndex: 1000,
    stack: false,
    buttons: {
      '取消': function() {
        _onDialogClose();
      },
      '確定發表': function() {
        if (_checkPost()) {
          _postTopic();
          _onDialogClose();
        }
      }
    }
  };
  
  var _onDialogClose = function() {
    $dlg.dialog('close');
  };
  
  var _checkPost = function() {
    // check topic
    var title = $('#post-title').val().replace(/^\s+|\s+$/, '');
    
    if (title.length == 0) {
      alert('請輸入主題!');
      return false;
    }
    
    var content = $('#post-desc').val().replace(/^\s+|\s+$/, '');
    if (content.length == 0) {
      alert('請輸入內容!');
      return false;
    }
    
    return true;
  };
  
  var _showPosting = function() {
    var wh = $(window).height(), ww = $(window).width();
    
    $('.ui-widget-shadow', $posting).css({
      left: (ww - 280) / 2 + 'px',
      top: (wh - 60) / 2 + 'px'
    });
    
    $('#posting-text').css({
      left: (ww - 280) / 2 + 'px',
      top: (wh - 60) / 2 + 'px'
    });
    
    $posting.removeClass('hide');
  };
  
  var _postTopic = function() {
    _showPosting();
    $.ajax({
      url: '/topic/create',
      type: 'post',
      data: $form.serialize(),
      dataType: 'json',
      success: function(resp) {
        if (resp.ok) {
          $('#posting-text').html('頁面切換中...');
          setTimeout(function(){
            location.href = "/forum/" + resp.forumLink + '/topic/' + resp.topicId;
          }, 1000);
        }
      }
    });
  };
  
  var _initUI = function() {
    $dlg.dialog(dlgOpt);
    $('#post-button').click(function(e) {
      $dlg.dialog('open');
    });
  };
  
  return {
    init: function() {
      _initUI();
    }
  };
  
})();

Forum.Show.init();
  
})(document);